package com.zyj.test.month1.day4;

/**
 * @author Yijia Zhang
 * @create 2024-04-25 23:53
 */
public class code0004 {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int len1 = nums1.length;
        int len2 = nums2.length;
        if (len1 > len2) {
            return findMedianSortedArrays(nums2, nums1);
        }
        int l = 0, r = nums1.length;
        int total = len1 + len2;
        int half = total >> 1;
        while (l <= r) {
            int mid = l + (r - l >> 1);
            int mid2 = half - mid;
            int left1 = mid > 0 ? nums1[mid - 1] : Integer.MIN_VALUE;
            int left2 = mid2 > 0 ? nums2[mid2 - 1] : Integer.MIN_VALUE;
            int right1 = mid < len1 ? nums1[mid] : Integer.MAX_VALUE;
            int right2 = mid2 < len2 ? nums2[mid2] : Integer.MAX_VALUE;
            if (left1 > right2) {
                r = mid - 1;
            } else if (right1 < left2) {
                l = mid + 1;
            } else {
                int leftMax = Math.max(left1, left2);
                int rightMin = Math.min(right1, right2);
                if ((len1 + len2) % 2 == 0) {
                    return (leftMax + rightMin) / 2.0;
                } else {
                    return rightMin;
                }
            }
        }
        return 0.0;

    }

}
